package com.example.fengyungo_user.activity.main;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.alipay.sdk.app.EnvUtils;
import com.alipay.sdk.app.PayTask;
import com.example.fengyungo_user.R;
import com.example.fengyungo_user.activity.BaseActivity;
import com.example.fengyungo_user.constant.OrderConstant;
import com.example.fengyungo_user.constant.PayConstant;
import com.example.fengyungo_user.constant.ResultConstant;
import com.example.fengyungo_user.constant.TextConstant;
import com.example.fengyungo_user.constant.UserConstant;
import com.example.fengyungo_user.domain.Order;
import com.example.fengyungo_user.domain.OrderDetailsDTO;
import com.example.fengyungo_user.utils.ActivityCollector;
import com.example.fengyungo_user.utils.CommonUtil;
import com.example.fengyungo_user.utils.OkHttpUtils;
import com.example.fengyungo_user.utils.ThreadPoolUtil;

import java.io.IOException;
import java.util.Map;

/**
 * @author 徐
 */
public class PayActivity extends BaseActivity {
    private static final String TAG = "PayActivity";

    /**
     * 支付测试
     */
    private Button testPay;

    private static final int SDK_PAY_FLAG = 101;

    private String info;

    private Context context;

    private TextView beginTv;

    private TextView endTv;

    private TextView priceTv;

    private TextView lengthTv;

    private TextView widthTv;

    private TextView heightTv;

    private TextView weightTv;

    private TextView noteTv;

    private TextView earliestTimeTv;

    private TextView latestTimeTv;

    private Button payLaterBtn;

    private Button payNowBtn;

    private ProgressBar progressBar;

    private OrderDetailsDTO orderDetailsDTO;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay);

        context = this;

        // 从intent获取数据
        Intent intent = getIntent();
        orderDetailsDTO = (OrderDetailsDTO) intent.getSerializableExtra(OrderConstant.ORDER_DETAILS_DTO);
        Log.d(TAG, "onCreate: orderDetailsDTO=" + orderDetailsDTO);

        initControls();

        // 沙箱测试
        EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
//        testPay = findViewById(R.id.btn_pay);
//        testPay.setOnClickListener((v) -> {
//            payToMall();
//        });

        // 稍后再付
        payLaterBtn.setOnClickListener((v) -> {
            // 设置支付状态为未支付
            orderDetailsDTO.setPayStatus(OrderConstant.NO_PAID);
            addOrder(false);
        });
        // 现在支付
        payNowBtn.setOnClickListener((v) -> {
            // 设置支付状态为已支付
            orderDetailsDTO.setPayStatus(OrderConstant.HAS_PAID);
            addOrder(true);
        });
    }

    /**
     * 初始化控件
     */
    private void initControls() {
        beginTv = findViewById(R.id.tv_begin);
        endTv = findViewById(R.id.tv_end);
        priceTv = findViewById(R.id.tv_price);
        lengthTv = findViewById(R.id.tv_length);
        widthTv = findViewById(R.id.tv_width);
        heightTv = findViewById(R.id.tv_height);
        weightTv = findViewById(R.id.tv_weight);
        noteTv = findViewById(R.id.tv_note);
        earliestTimeTv = findViewById(R.id.tv_earliest_time);
        latestTimeTv = findViewById(R.id.tv_latest_time);

        payLaterBtn = findViewById(R.id.btn_pay_later);
        payNowBtn = findViewById(R.id.btn_pay_now);

        progressBar = findViewById(R.id.progress_bar);

        // 修改显示
        beginTv.setText(orderDetailsDTO.getBegin());
        endTv.setText(orderDetailsDTO.getEnd());
        priceTv.setText(String.valueOf(orderDetailsDTO.getPrice()));
        lengthTv.setText(String.format("%s%s", orderDetailsDTO.getLength(), OrderConstant.CM));
        widthTv.setText(String.format("%s%s", orderDetailsDTO.getWidth(), OrderConstant.CM));
        heightTv.setText(String.format("%s%s", orderDetailsDTO.getHeight(), OrderConstant.CM));
        weightTv.setText(String.format("%s%s", orderDetailsDTO.getWeight(), OrderConstant.G));
        noteTv.setText(orderDetailsDTO.getNote());
        latestTimeTv.setText(orderDetailsDTO.getLatestTime());
        earliestTimeTv.setText(orderDetailsDTO.getEarliestTime());
    }

    /**
     * 跳转到主页
     */
    private void intentToMainFragment() {
        // 跳转到主页
        ActivityCollector.finishOtherActivity(MainActivity.class);
    }

    /**
     * 向商家付款
     */
    private void payToMall() {
        // 订单
        Order order = new Order();
        order.setBegin(orderDetailsDTO.getBegin());
        order.setEnd(orderDetailsDTO.getEnd());
        order.setPrice(orderDetailsDTO.getPrice());
        order.setNumber(orderDetailsDTO.getNumber());
        // 订单信息
        String orderInfo = getOrderStr(order);
        Log.d(TAG, "payToMall: orderInfo=" + orderInfo);
        Runnable payRunnable = () -> {
            PayTask alipay = new PayTask(this);
            Map<String, String> result = alipay.payV2(orderInfo, true);
            Message msg = new Message();
            Log.d(TAG, "payToMall: result=" + result);
            msg.what = SDK_PAY_FLAG;
            msg.obj = result;
            mHandler.sendMessage(msg);
        };
        // 必须异步调用
        ThreadPoolUtil.execute(payRunnable);
    }

    /**
     * 支付后点击完成或取消支付执行
     */
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Map<String, String> result = (Map<String, String>) msg.obj;
            String resultStatus = result.get(PayConstant.RESULT_STATUS);
            String memo = result.get(PayConstant.MEMO);
            // 支付成功
            if (resultStatus.equals(PayConstant.PAY_SUCCESS)) {
                Toast.makeText(context, OrderConstant.ORDER_ADD_SUCCESS, Toast.LENGTH_SHORT).show();
                intentToMainFragment();
            } else {
                // 支付失败
                // 修改支付状态为未支付、订单状态为已取消
                setOrderNotFinished();
                Toast.makeText(context, memo, Toast.LENGTH_SHORT).show();
            }
            Log.d(TAG, "handleMessage: " + result);
        }
    };

    /**
     * 发送Order到后端，从后端获取orderStr
     *
     * @param order Order
     * @return String
     */
    private String getOrderStr(Order order) {
        info = null;
        Runnable runnable = () -> {
            String jsonString = JSONObject.toJSONString(order);
            try {
                String responseData = OkHttpUtils.post(UserConstant.URL_USER_ALIPAY, jsonString);
                JSONObject jsonObject = JSONObject.parseObject(responseData);
                int code = jsonObject.getInteger(ResultConstant.CODE);
                String msg = jsonObject.getString(ResultConstant.MSG);
                String data = jsonObject.getString(ResultConstant.DATA);
                if (code == ResultConstant.SUCCESS) {
                    info = data;
                } else {
                    runOnUiThread(() -> {
                        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
                        info = TextConstant.ERROR;
                    });
                }
            } catch (IOException e) {
                e.printStackTrace();
                runOnUiThread(() -> {
                    Toast.makeText(context, TextConstant.INTERNET_ERROR, Toast.LENGTH_SHORT).show();
                    info = TextConstant.ERROR;
                });
            }
        };
        ThreadPoolUtil.execute(runnable);
        while (info == null) {
        }
        return info;
    }

    /**
     * 发布订单
     */
    private void addOrder(boolean payNow) {
        progressBar.setVisibility(View.VISIBLE);
        Runnable runnable = () -> {
            // 以当前时间设置订单号number
            orderDetailsDTO.setNumber(CommonUtil.initIdByNowTime());
            String jsonString = JSONObject.toJSONString(orderDetailsDTO);
            String url = UserConstant.URL_USER_USER + "/add";
            try {
                String responseData = OkHttpUtils.post(url, jsonString);
                JSONObject jsonObject = JSONObject.parseObject(responseData);
                int code = jsonObject.getInteger(ResultConstant.CODE);
                String msg = jsonObject.getString(ResultConstant.MSG);
                if (code == ResultConstant.SUCCESS) {
                    runOnUiThread(() -> {
                        progressBar.setVisibility(View.GONE);
                        if (payNow) {
                            Log.d(TAG, "addOrder: payNow");
                            payToMall();
                        } else {
                            Toast.makeText(context, OrderConstant.ORDER_ADD_SUCCESS, Toast.LENGTH_SHORT).show();
                            intentToMainFragment();
                        }
                    });
                } else {
                    runOnUiThread(() -> {
                        progressBar.setVisibility(View.GONE);
                        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
                    });
                }
            } catch (IOException e) {
                e.printStackTrace();
                runOnUiThread(() -> {
                    progressBar.setVisibility(View.GONE);
                    Toast.makeText(context, TextConstant.INTERNET_ERROR, Toast.LENGTH_SHORT).show();
                });
            }
        };
        ThreadPoolUtil.execute(runnable);
    }

    /**
     * 设订单未完成，设置订单为未支付、状态为取消
     */
    private void setOrderNotFinished() {
        Runnable runnable = () -> {
            try {
                String url = UserConstant.URL_USER_USER + "/notFinished/" + orderDetailsDTO.getNumber();
                String responseData = OkHttpUtils.put(url, "");
                JSONObject jsonObject = JSONObject.parseObject(responseData);
                int code = jsonObject.getInteger(ResultConstant.CODE);
                String msg = jsonObject.getString(ResultConstant.MSG);
                if (code == ResultConstant.SUCCESS) {
                    runOnUiThread(() -> {
                        Toast.makeText(context, OrderConstant.ORDER_NOT_FINISHED, Toast.LENGTH_SHORT).show();
                    });
                } else {
                    runOnUiThread(() -> {
                        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
                    });
                }
            } catch (IOException e) {
                e.printStackTrace();
                runOnUiThread(() -> {
                    Toast.makeText(context, TextConstant.INTERNET_ERROR, Toast.LENGTH_SHORT).show();
                });
            }
        };
        ThreadPoolUtil.execute(runnable);
    }
}